<template>
  <PageContainer>
    <Header title="文件设置" :data="itemData">
      <template>
        <view v-if="itemData" class="hb-px-4">
          <FileItem :item="itemData!" :show-setting="false" />
        </view>
      </template>
    </Header>
    <view>
      <view class="hb-m-4 hb-py-3 hb-px-4 hb-bg-white hb-box-shadow-base hb-rounded-xl">
        <TmText _class="hb-font-bold hb-mb-2" label="谁可以调用" :font-size="28" />
        <view class="hb-py-2">
          <!-- 私密 -->
          <view
            class="hb-flex hb-items-center hb-gap-2 hb-mb-3"
            @click="handleChangePermission(FileUploadPolicyEnum.ALL_MEMBERS)"
          >
            <CustomRadio :checked="fileCallPolicy === FileUploadPolicyEnum.ALL_MEMBERS" />
            <TmText label="所有成员" :font-size="24" />
            <TmText label="所有加入圈子的成员均可调用" color="#969799" :font-size="24" />
          </view>
          <!-- 公开 -->
          <view
            class="hb-flex hb-items-center hb-gap-2 hb-mb-3"
            @click="handleChangePermission(FileUploadPolicyEnum.ADMINS_ONLY)"
          >
            <CustomRadio :checked="fileCallPolicy === FileUploadPolicyEnum.ADMINS_ONLY" />
            <TmText label="仅管理员" :font-size="24" />
            <TmText label="仅管理员可以调用" color="#969799" :font-size="24" />
          </view>
          <!-- 部分可调用 -->
          <view
            class="hb-flex hb-items-center hb-gap-2 hb-mb-3"
            @click="handleChangePermission(FileUploadPolicyEnum.CUSTOM)"
          >
            <CustomRadio :checked="fileCallPolicy === FileUploadPolicyEnum.CUSTOM" />
            <TmText label="部分成员可调用" :font-size="24" />
          </view>
          <!-- 指定权限 -->
          <view class="hb-ml-7 hb-rounded-lg hb-bg-[#F7F8FA]">
            <view
              class="permission-wrapper"
              :class="{ expanded: fileCallPolicy === FileUploadPolicyEnum.CUSTOM }"
            >
              <!-- 选择好友 -->
              <view class="hb-p-3 hb-border-b hb-border-solid hb-border-[#EBEDF0]">
                <view class="hb-flex hb-items-center hb-flex-wrap hb-gap-2 hb-mb-2">
                  <TmImage
                    v-for="(item, index) in selectedMembers"
                    :key="index"
                    :src="item.content"
                    :width="72"
                    :height="72"
                    :round="2"
                  />
                </view>
                <TmButton
                  icon="tmicon-plus"
                  :margin="[0, 0, 0, 16]"
                  :width="200"
                  :height="60"
                  outlined
                  :border="1"
                  color="primary"
                  label="选择成员"
                  :font-size="24"
                  :round="12"
                  @click="handleSelectMembers"
                />
                <TmText label="选中的成员可调用" color="#969799" :font-size="24" />
              </view>
            </view>
          </view>
        </view>
      </view>
      <BottomSubmit
        :hide-cancel-btn="false"
        cancel-btn-label="移除文件"
        cancel-btn-color="#EA5E0E"
        cancel-btn-border-color="#EA5E0E"
        submit-btn-label="保存设置"
        @cancel="handleDeleteFile"
        @submit="handleSaveSetting"
      />
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* circleFileSetting 文件设置 */
  import { FileUploadPolicyEnum } from '@/enums/PublicEnum';
  import FileItem from '../circleDetail/components/FileItem.vue';
  import { CircleFileListResult, CircleMemberListResult } from '@/api/contact/types';
  import { FileAuthInfo } from '@/api/knowledgeBase/types';
  import {
    circleFilePermMemberList,
    removeCircleSharedFile,
    setCircleFilePerm,
  } from '@/api/contact';
  import { Toast } from '@/utils';
  import { CircleFileSetting } from '@/router/types/modules';

  const itemData = ref<CircleFileListResult>();
  const fileCallPolicy = ref<FileUploadPolicyEnum>(FileUploadPolicyEnum.ALL_MEMBERS);
  const selectedMembers = ref<FileAuthInfo[]>([]);
  const circlesId = ref<number>(0);
  let success: CircleFileSetting['success'];

  customOnload<'circleFileSetting'>((op) => {
    circlesId.value = op.circleId;
    itemData.value = op.data;
    fileCallPolicy.value = op.data.fileCallPolicy;
    success = op.success;
    circleFilePermMemberList({ circleFileId: op.data.id }).then(
      (res) => (selectedMembers.value = res),
    );
  });

  function handleChangePermission(permission: FileUploadPolicyEnum) {
    fileCallPolicy.value = permission;
  }

  function handleSelectMembers() {
    navigateTo({
      name: 'selectMembers',
      options: {
        id: circlesId.value,
        type: 'member',
        selected: selectedMembers.value.map((item) => item.id),
        success: (data: CircleMemberListResult[]) => {
          selectedMembers.value = data.map((item) => ({
            id: item.id,
            content: item.iconFileUrl,
          }));
        },
      },
    });
  }

  /** 删除文件 */
  function handleDeleteFile() {
    uni.showModal({
      title: '移除文件',
      content: '确定要把本文件从圈子共享文件列表移除吗？',
      confirmText: '确认移除',
      cancelColor: '#999996',
      cancelText: '取消',
      confirmColor: '#EA5E0E',
      success: ({ confirm }) => {
        if (confirm) {
          removeCircleSharedFile({ circleFileId: itemData.value!.id }).then(() => {
            success?.('delete');
            Toast({
              title: '删除成功',
              success: () => {
                navigateBack();
              },
            });
          });
        }
      },
    });
  }

  const handleSaveSetting = () => {
    const memberIds = selectedMembers.value.map((item) => item.id);
    if (memberIds.length === 0 && fileCallPolicy.value === FileUploadPolicyEnum.CUSTOM) {
      Toast('请选择成员');
      return;
    }
    setCircleFilePerm({
      circleFileId: itemData.value!.id,
      fileCallPolicy: fileCallPolicy.value,
      memberIds: fileCallPolicy.value === FileUploadPolicyEnum.CUSTOM ? memberIds : [],
    }).then(() => {
      success?.();
      Toast({
        title: '保存成功',
        success: () => navigateBack(),
      });
    });
  };
</script>

<style lang="scss" scoped>
  /* 内容样式 */
  .permission-wrapper {
    max-height: 0;
    overflow: hidden;
    opacity: 0;
    transform: translateY(-10px);
    transition: max-height 0.5s cubic-bezier(0, 1, 0, 1), opacity 0.3s ease, transform 0.3s ease;

    &.expanded {
      max-height: 2000px; /* 足够大的值以容纳内容 */
      opacity: 1;
      transform: translateY(0);
      transition: max-height 1s ease-in-out, opacity 0.5s ease, transform 0.5s ease;
    }
  }
</style>
